<script lang="ts" setup>
import { ref } from 'vue'
import { getFreeTop, uploadAudio, getFreeContent } from '@/services/api'
import { useSubPage } from './composables'
import { BASE_URL } from '@/config'
import AudioWave from '@/utils/audio_wave'
import { useScrollUpdownBottomContent, useWebsocket } from '@/hooks'
import TnLineProgress from '@tuniao/tnui-vue3-uniapp/components/line-progress/src/line-progress.vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import { onLoad, onShow, onReady, onUnload, onHide } from '@dcloudio/uni-app'
import { nextTick } from 'vue'
const { navBarInfo, navbarInitFinishHandle } = useSubPage()
const progressPercent = ref(100)
const topNum = ref(10000)
const typeStatus = ref('start') // none未开始/loading加载中/start已开始
const chatBtnStatus = ref(1) //1初始化2开始录音3结束录音
const isShowText = ref(false)
const tipsList = ref([])
const headImg = ref('')
const userGender = ref(1)
const inputText = ref('')
const isUnload = ref(false)
const showPopup = ref(false)
const roleName = ref('')
const isPlayEnd = ref(true)
const isDisabledBtn = ref(false)
const recorderManager = uni.getRecorderManager()
const innerAudioContext = uni.createInnerAudioContext()
innerAudioContext.autoplay = true
const isShowChatBg = ref(false)
const newNormalArr = ref([])
const chatBg = ref(
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/free-bg.gif'
)
const smileBg = ref(
  'http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/free-bg.jpg'
)
const translateBlack = ref('../../static/imgs/icons/translate_black.png')
const translateBlue = ref('../../static/imgs/icons/translate_blue.png')
const duration = ref(3600) //执行的时间
const {
  connectWebSocketComment,
  connectWebSocket,
  handleClickVideo,
  handleCloseVideo,
  base64toJson,
  webSocketSendMp3,
  webSocketSendComment,
  webSocketSend,
  textTranslate,
  handleDebounce,
  handlePlayVideo,
  handleGeneratePath,
  encodeWAV,
  toBase64,
} = useWebsocket()
const pageId = ref<Number>(0)
const animation = ref(false)
const skillsMessage = ref({
  // platform: 'qwen',
  platform: 'gpt',
  // platform: 'kimi',
  messages: [],
})
// const platform = ref('qwen')
const platform = ref('gpt')
const tips = ref('')
// const platform = ref('kimi')
const playUrl = ref('')
const curPromptTips = ref()
const recordList = ref([])
const allTipsList = ref()
const lineArr = ref([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
const timerInter = ref(null)
const audioWave = ref()
const loading = ref('none')
const onUnloadType = ref(false)
onLoad((option: any) => {
  // 声波
  audioWave.value = new AudioWave('#audio-canvas', {
    horizonPadding: 40,
    onStop: (res) => {
      // console.log(res,"rerere")
      // 处理下一段音频（如果有的话）
      // onAudioEndHandler(playAudioIndex);
    },
    onError: console.error,
  })
  audioWave.value.clearTimer() //停止播放
  const { id, name, picture, gender, type } = option
  pageId.value = Number(id)
  userGender.value = gender
  // 是否为大图lily练口语
  if (type == 0) {
    roleName.value = name
    getDetail(pageId.value)
  } else {
    // 自动获取并播放
    getBaseInfo(pageId.value)
  }

  startWatch()
  handleStart()
})

onShow(() => {})

onReady(() => {
  autoScroll()
})

onHide(() => {
  audioWave.value.stopAudio() //停止播放
  // requestTask.abort()
  if (timerInter.value) {
    clearInterval(timerInter.value)
    timerInter.value = null
  }

  handleCloseVideo()
  endRecord()
})

onUnload(() => {
  onUnloadType.value = true
  audioWave.value.stopAudio() //停止播放
  if (timerInter.value) {
    clearInterval(timerInter.value)
    timerInter.value = null
  }
  timerInter.value = null
  isUnload.value = true
  audioWave.value = null
  handleCloseVideo()
  endRecord()
})
const clearTimerInter = () => {
  setInterval(function () {
    if (timerInter.value != null) {
      clearInterval(timerInter.value)
      timerInter.value = null
    }
  }, 50)
}
const handleStart = () => {
  typeStatus.value = 'loading'
  //等进度条加载完毕，开始播放三句对话
  // setTimeout(function () {
  // 	typeStatus.value = 'start'
  // 	isShowChatBg.value = true
  // 	handleNormalPlay()
  // }, duration.value)

  typeStatus.value = 'start'
  isShowChatBg.value = true
}
const handleClick = async (type: string, value: string, index, source) => {
  switch (type) {
    case 'fanyiAll':
      isShowText.value = !isShowText.value
      autoScroll()
      break
    case 'open':
      if (chatBtnStatus.value != 1) {
        showPopup.value = true
      }

      break
    case 'send':
    let fanyiStr = await handleFanyi(value)
      recordList.value.push({
        type: 2,
        content: value,
        result: '',
        isTranslate: true,
        role: 'user',
        cn:fanyiStr,
      })

      tipsList.value = []
      showPopup.value = false
      setSkills(value, 'user')
      break
    case 'play':
      // value.split('.').forEach((data) => {
      // Chinese中文 | English英文
      webSocketSendMp3(value, userGender.value != 1 ? 'Chinese' : '').then(
        async (res) => {
          if (source == 1) {
            // recordList.value[index].isPlay = true
            recordList.value = recordList.value.map((item, i) => {
              return {
                ...item,
                isPlay: i === index,
              }
            })
          }
          if (source == 2) {
            tipsList.value = tipsList.value.map((item, i) => {
              return {
                ...item,
                isPlay: i === index,
              }
            })
          }
          let newUrl = await handleGeneratePath(res)
          handleClickVideo(newUrl).then(() => {
            if (source == 1) {
              recordList.value[index].isPlay = false
            }
            if (source == 2) {
              tipsList.value[index].isPlay = false
            }
          })
        }
      )
      break
    case 'fanyi':
      textTranslate(value)
        .then(
          (res) => {
            tipsList.value[index].translate = res
            tipsList.value[index].isTranslate = true
          },
          () => {
            translateLongTip()
          }
        )
        .catch(() => {
          translateLongTip()
        })
      autoScroll()
      break
  }
}

const handleClose = () => {
  handleCloseVideo()
  uni.navigateBack()
}

// AI进行翻译
const handleFanyi = (value: string) => {
  return new Promise((resolve, reject) => {
    textTranslate(value)
      .then((res) => {
        resolve(res)
      })
      .catch(() => {})
  })
}

// 頁面滾動
const autoScroll = () => {
  console.log('autoscroll');

  // topNum.value = 10000
  uni.pageScrollTo({
    scrollTop: 10000, // 假设页面很长，滚动到一个很大的值，从而滚动到底部
    duration: 300, // 滚动动画时长，默认300ms
  })
  topNum.value = topNum.value + 10000
}

// 开始录音
const startRecord = () => {
  handleCloseVideo()
  animation.value = true
  connectWebSocket().then((res: string) => {
    if (res != '') {
      handleFanyi(res).then((data) => {
        recordList.value.push({
          content: res,
          cn: data,
          role: 'user',
        })
		if(onUnloadType.value == false){
			autoScroll()
		}
        setSkills(res, 'user')
      })
    } else {
      uni.showToast({
        title: '未识别到文字',
        icon: 'none',
      })
    }
  })
  recorderManager.start({
    duration: 600000, // 600000（10 分钟）,默认值 60000（1 分钟）
    numberOfChannels: 1, // 录音通道数，有效值 1/2
    frameSize: 1,
    format: 'pcm', // 音频格式
    sampleRate: 16000, // 采样率
  })
}

// 结束录音
const endRecord = () => {
  animation.value = false
  recorderManager.stop()
}

// 获取对话参考
const getChatAiTag = (value) => {
  let allText = ''
  let messageData = {
    platform: platform.value,

    messages: [
      {
        content: `Role:中国小学英语老师 Profile: - author: 中国小学英语老师 - version: 0.1 - language: 英文 - description: 你是一个中国小学一年级的英语老师，擅长跟你的学生进行简单的场景对话，帮助你的学生在特定的场景下学习英文口语。 Rules: - 根据给定的对话主题<Scene>，你先对学生发起对话。 -在整个对话中，你每次发起一个提问，都讲根据对话的上下文提供3个参考回答 --每个回答的字数在100token以内 -- 回答的范围和内容过程中，涉及到的单词包含在<Words>中，请不要使用超过<Words>中的单词 Scene： - 对话的主题是《见面问候》 - 对话的主旨的让学生能够说出各种学习用品的英语单词 Words： -Good morning / afternoon / evening -How are you? -I'm fine, thank you. 。 -Nice to meet you. -What's your name? -My name is [Name]. -Goodbye / Bye -Thank you / Thanks -You're welcome. -Please -Sorry -Excuse me -Hello, everyone!" −What's this? −This is a ... . −How many ... do you have? - −I have ... −Do you have a ...? −Yes, I do. / No, I don't. −Show me your ...`,
        role: 'system',
      },
      ...skillsMessage.value.messages.slice(1),
      {
        content:
          ' 根据对话的上下文提供3个参考答案' +
          value +
          '这句话,请按照此JSON格式输出 [{"line"\:"one"\},{"line"\:"two"\},{"line"\:"three"\}] 不允许返回与此格式无关的内容,不允许返回中文，只可以英文回复',
        role: 'system',
      },
    ],
  }
  let str = ''
  const requestTask = uni.request({
    url: `${BASE_URL}/enteacher/aichat`,
    timeout: 15000,
    responseType: 'text',
    method: 'POST',
    enableChunked: true,
    data: messageData,
    success: (response) => {},
    fail: (error) => {},
  })
  requestTask.onChunkReceived(function (res) {
    const uint8Array = new Uint8Array(res.data)
    let text = String.fromCharCode.apply(null, uint8Array)
    switch (platform.value) {
      case 'gpt':
        try {
          allText += text
          if (allText.indexOf('[DONE]') != -1) {
            let dataArrGpt = allText.split('data:')
            dataArrGpt.map((item, index) => {
              if (item != '' && item.indexOf('[DONE]') == -1) {
                let obj = JSON.parse(item)
                str += ![undefined].includes(obj.choices[0].delta.content)
                  ? obj.choices[0].delta.content
                  : ''
              }
            })

            tipsList.value = JSON.parse(str)
          }
        } catch (err) {
          console.log(err)
          requestTask.abort()
        }

        break
    }
  })
}
const setMp3Url = (uint8Array) => {
  return new Promise((resolve, reject) => {
    let baseData = toBase64(uint8Array.buffer, 'normal')
    let fileName = new Date().getTime()
    let obj = {
      file_name: fileName + '.mp3',
      base64_file: baseData, // Base64 编码的文件内容
      project_name: 'userMp3',
    }
    uploadAudio(obj).then((res) => {
      const { message, data } = res
      if (message === 'pong') {
        resolve({
          code: 0,
          url: data.fileUrl,
        })
      } else {
        reject({ code: '400', msg: '未返回音频' })
      }
    })
  })
}
const handleClosePopup = () => {
  showPopup.value = false
}
const onChatBtnClick = async () => {
  //chatBtnStatus状态： 1初始化 2开始录音 3结束录音
  switch (chatBtnStatus.value) {
    case 1:
      recordList.value = [{}]
      isDisabledBtn.value = true
      isShowChatBg.value = true

      // 播放
      let mp3Str = await webSocketSendMp3(
        curPromptTips.value,
        userGender.value != 1 ? 'Chinese' : ''
      )
      let newUrl = await handleGeneratePath(mp3Str, 'array')
      let curData = await setMp3Url(newUrl.uint8Array)
      if (curData.code == 0) {
        recordList.value[0].url = curData.url
        audioWave.value.startAudio(curData.url, true)
      } else {
        recordList.value[0].url = newUrl
        await handlePlayVideo(recordList.value[0].url)
      }
      // 打字效果
      let index = 0
      const streamOutput = async () => {
        if (index < curPromptTips.value.length) {
          let currentText = curPromptTips.value.substring(0, index + 1)
          index++
          recordList.value[0].content = currentText
        } else {
          if (onUnloadType.value == false) {
            clearInterval(timerInter.value)
            // 无需调用获取三句提示
            // getChatAiTag(recordList.value[0].content)
            let fanyiStr = await handleFanyi(recordList.value[0].content)
            recordList.value[0].cn = fanyiStr
            skillsMessage.value.messages.push({
              content: recordList.value[0].content,
              role: 'system',
            })
            skillsMessage.value.messages.push({
              content: tips.value,
              role: 'system',
            })
            autoScroll()
          }
        }
      }
      autoScroll()
      timerInter.value = setInterval(streamOutput, 50)
      // await handlePlayVideo(recordList.value[0].url)
      isDisabledBtn.value = false
      isShowChatBg.value = false
      chatBtnStatus.value = 2
      break
    case 2:
      if (loading.value == 'loading') {
        uni.showToast({
          title: 'AI回复中',
          icon: 'none',
        })
        return
      }
      audioWave.value.stopAudio() //停止播放
      startRecord()
      chatBtnStatus.value = 3
      break
    case 3:

      endRecord()

      chatBtnStatus.value = 2
      break
  }
}

const buf2hex = (arrayBuffer) => {
  let hex = ''
  let uint8Array = new Uint8Array(arrayBuffer)
  for (let i = 0; i < uint8Array.length; i++) {
    // 将字节转换为16进制字符串，并添加到hex中
    hex += uint8Array[i].toString(16).padStart(2, '0') // 使用padStart确保总是两位数
  }
  return hex
}

const hexToString = (str: any) => {
  var val = '',
    len = str.length / 2
  for (var i = 0; i < len; i++) {
    val += String.fromCharCode(parseInt(str.substr(i * 2, 2), 16))
  }
  return utf8to16(val)
}

//处理中文乱码问题
const utf8to16 = (str) => {
  var out, i, len, c
  var char2, char3
  out = ''
  len = str.length
  i = 0
  while (i < len) {
    c = str.charCodeAt(i++)
    switch (c >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        out += str.charAt(i - 1)
        break
      case 12:
      case 13:
        char2 = str.charCodeAt(i++)
        out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f))
        break
      case 14:
        char2 = str.charCodeAt(i++)
        char3 = str.charCodeAt(i++)
        out += String.fromCharCode(
          ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0)
        )
        break
    }
  }
  return out
}

const setSkills = (res: string, type: string) => {
  clearInterval(timerInter.value)
  timerInter.value = 'none'
  loading.value = 'loading'
  let strGpt = ''
  skillsMessage.value.messages.push({
    content: res,
    role: type || 'user',
  })

  if (type == 'system') {
    skillsMessage.value.messages.push({
      content: 'Hello',
      role: 'user',
    })
  }

  recordList.value.push({
    type: 1,
    content: '',
    result: '',
    filename: '',
    isTranslate: false,
    role: 'assistant',
  })
  console.log(skillsMessage.value,'skillsMessage.value');

  const requestTask = uni.request({
    url: `${BASE_URL}/enteacher/aichat`,
    timeout: 15000,
    responseType: 'text',
    method: 'POST',
    enableChunked: true,
    data: skillsMessage.value,
    success: async (response) => {
      skillsMessage.value.messages.push({
        content: allTipsList.value,
        role: 'assistant',
      })
      setTimeout(() => {
        getChatAiTag(allTipsList.value)
      }, 1300)
    },
    fail: (error) => {},
  })
  requestTask.onChunkReceived(function (res) {
    const data16 = buf2hex(res.data) // ArrayBuffer转16进制
    const text = hexToString(data16) // 16进制转字符串
    switch (platform.value) {
      case 'gpt':
        try {
          let dataArrGpt = text.split('data:')
          dataArrGpt.map(async (item) => {
            if (item != '' && item.indexOf('[DONE]') != 1) {
              try {
                let obj = JSON.parse(item)
                strGpt += ![null, undefined, ''].includes(
                  obj.choices[0].delta.content
                )
                  ? obj.choices[0].delta.content
                  : ''
              } catch (err) {}
            }
            if (item.indexOf('[DONE]') == 1) {
              let mp3Str = await webSocketSendMp3(
                strGpt,
                userGender.value != 1 ? 'Chinese' : ''
              )
              let newUrl = await handleGeneratePath(mp3Str, 'array')
              let index = 0
              const streamOutput = async () => {
                if (index < strGpt.length) {
                  let currentText = strGpt.substring(0, index + 1)
                  index++
                  recordList.value[recordList.value.length - 1].content =
                    currentText
                  autoScroll()
                } else {
                  clearInterval(timerInter.value)
                  loading.value = ''
                  autoScroll()
                  // recordList.value[recordList.value.length - 1].cn = strGpt
                  let fanyiStr = await handleFanyi(allTipsList.value)
                  recordList.value[recordList.value.length - 1].cn = fanyiStr
                  console.log(recordList.value,'recordList.value');

                  nextTick(()=>{
                    autoScroll()
                  })


                  //自动播放ai回答的内容
                }
              }
			  if(onUnloadType.value == false){
				timerInter.value = setInterval(streamOutput, 50)
			  }
              audioWave.value.startAudio(newUrl, false)
              let curData = await setMp3Url(newUrl.uint8Array)
              if (curData.code == 0) {
                audioWave.value.startAudio(curData.url, true)
              } else {
                await handlePlayVideo(newUrl)
              }
            }
            // onplayTitle(
            // 	allTipsList.value,
            // 	'Chinese'
            // )
          })
          allTipsList.value = strGpt
        } catch (err) {
          console.log(err)
          requestTask.abort()
        }

        break
    }

    // autoScroll()
  })
}

const startWatch = () => {
  // let lineArr = []
  var lastFrame = []
  recorderManager.onStop(function (res) {
    // 监听最后一帧
    // 基础
    webSocketSend(lastFrame, true).then((res) => {
      if (res == 'success') {
      }
    })
    lineArr.value = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    let tempFile = res.tempFilePath //音频文件地址
    // #ifdef MP-WEIXIN
    const fs = uni.getFileSystemManager()
    // 评分
    fs.readFile({
      //读取文件并转为ArrayBuffer
      filePath: tempFile,
      success(res) {
        // audioWave.value.startAudio(res.data, true);
      },
    })
    // #endif
  })
  recorderManager.onFrameRecorded(function (res) {
    const { frameBuffer, isLastFrame } = res
    lastFrame = frameBuffer
    let newFrameBuffer = new Uint8Array(frameBuffer)
    // 基础
    webSocketSend(frameBuffer, isLastFrame).then((res) => {
      if (res == 'success') {
      }
    })
    const intArray = new Int16Array(frameBuffer)
    // 到这一步还能理解，但是 intArray 返回的切片数据太多，才疏学浅没有明白里面具体代表的含义，百度也找了很久没什么资料可以参考，最后找规律发现在每一条的最大值基本代表了现在的振幅，所以直接一步到位取了个最大值，有懂的朋友可以不吝赐教一下
    const amplitude = Math.max(...intArray) // 计算当前帧的振幅
    // 最后将每次的振幅保存下来，进行绘制即可 ， 3276.8 是 根据 采样率及编码码率及你的波形图的最高高度得出的一个合适值， 这个可以随便试一试就出来了
    lineArr.value.push(amplitude / 3276.8)
    lineArr.value.shift()
  })
}
const getBaseInfo = async (id) => {
  getFreeContent(id).then((res) => {
    const newStr = []
    const { code, data } = res
    if (code === 0) {
      // 拿到英文
      // recordList.value = JSON.parse(data.chatIntroduce).map((item: any) => {
      //   return {
      //     content: item,
      //     role: 'assistant',
      //   }
      // })
      roleName.value = data.name
      headImg.value = data.picture
      //翻译中文
      // recordList.value.forEach(async (item, index) => {
      //   item.cn = await handleFanyi(item.content)
      // })
      tips.value = data.tips
      curPromptTips.value = data.chatQuestions
      onChatBtnClick()
    }
  })
}
const getDetail = (id) => {
  return new Promise<void>((resolve, reject) => {
    getFreeTop().then((res) => {
      const newStr = []
      const { code, data } = res
      if (code === 0) {
        // 拿到英文
        // recordList.value = JSON.parse(data.chatIntroduce).map((item: any) => {
        //   return {
        //     content: item.english,
        //     role: 'assistant',
        //   }
        // })
        roleName.value = data.name
        headImg.value = data.picture

        //翻译中文
        // recordList.value.forEach(async (item, index) => {
        //   item.cn = await handleFanyi(item.content)
        // })
        tips.value = data.tips
        curPromptTips.value = data.chatQuestions
        onChatBtnClick()
      }
    })
  })
}

// const getDetail = (id) => {
//   return new Promise<void>((resolve, reject) => {
//     getFreeTop().then((res) => {
//       const newStr = []
//       const { code, data } = res
//       if (code === 0) {
//         // 拿到英文及中文
//         newNormalArr.value = JSON.parse(data.chatIntroduce).map((item: any) => {
//           return {
//             content: item.english,
//             role: 'assistant',
//           }
//         })
//         curPromptTips.value = data.chatQuestions
//         const testFun = async function (i) {
//           if (i >= newNormalArr.value.length) {
//             return
//           } else {
//             let fanyiStr = await handleFanyi(newNormalArr.value[i].content)
//             newNormalArr.value[i].cn = fanyiStr
//             let mp3Str = await webSocketSendMp3(
//               newNormalArr.value[i].content,
//               'Chinese'
//             )
//             let newUrl = await handleGeneratePath(mp3Str)
//             newNormalArr.value[i].url = newUrl
//           }
//           i++
//           testFun(i)
//           return
//         }
//         testFun(0)
//       }
//     })
//   })
// }
const onplayTitle = (value, type) => {
  isDisabledBtn.value = true
  isShowChatBg.value = true
  if (!isUnload.value) {
    // Chinese中文 | English英文
    webSocketSendMp3(value, type).then(async (res) => {
      let newUrl = await handleGeneratePath(res)
      if (!isUnload.value) {
        handleClickVideo(newUrl).then(() => {
          isDisabledBtn.value = false
          isShowChatBg.value = false
        })
      }
    })
  }
}
</script>
<template>
    <page-meta page-style="overflow:hidden"></page-meta>
  <view class="page">
    <!-- <image
      class="page-bg"
      :src="isShowChatBg ? chatBg : smileBg"
      mode="aspectFill"
    ></image> -->
    <view>
      <image class="head-img" :src="headImg" mode="aspectFill"></image>
      <!-- {{ loading }} -->
      <canvas id="audio-canvas" type="2d" />
    </view>
    <!-- 详细信息 -->
    <view class="info" v-if="typeStatus == 'start'">
      <view class="icons mb-24">
        <view
          class="icons-list flex flex-ai-center flex-js-center active mr-6"
          @click="handleClick('fanyiAll')"
        >
          <image
            :src="isShowText ? translateBlue : translateBlack"
            style="border-radius: initial"
          ></image>
        </view>
        <!-- <view
          class="icons-list flex flex-ai-center flex-js-center"
          @click="handleClick('open')"
        >
          <image
            src="../../static/imgs/icons/tips_icon.png"
            style="border-radius: initial"
          ></image>
        </view> -->
      </view>
      <scroll-view
        class="tn-text-justify info-content"
        scroll-y="true"
        style="height: calc(100% - 256rpx)"
        :scroll-top="topNum"
      >
        <view
          v-for="(item, index) in recordList"
          :key="index"
          :class="{ 'float-right': item.role == 'user' }"
        >
          <view class="items-list pa-6 mb-8">
            <view
              v-if="item.content"
              class="font-size-12 content-text flex"
              :class="{ 'user-text': item.role == 'user' }"
            >
              <view class="title-dot mr-8">·</view>
              <view>
                <view style="font-size: 36rpx;line-height: 46rpx">{{ item.content }}</view>
                <view
                  class="mt-8 font-size-12 cn-text"
                  :class="{ 'user-text': item.role == 'user' }"
                  v-if="isShowText"
                  >{{ item.cn }}</view
                >
              </view>
            </view>
            <image
              v-else
              src="http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/loading_ai.gif"
              mode="widthFix"
              class="loading-ai-gif"
            ></image>
          </view>
          <!-- 	<view class="items-list pa-12 mb-8 items-status">
						<view class="font-w-bold">...</view>
					</view>
					<view class="items-list pa-12 mb-8 items-status">
						<view class="font-w-bold">...</view>
					</view> -->
        </view>
      </scroll-view>
      <view class="recording-box" v-if="animation">
        <view class="recording-gif">
          <view class="flex flex-ai-center flex-js-center">
            <view
              v-for="(item, index) in lineArr"
              class="mr-6"
              style="
                display: inline-table;
                background: rgb(75, 73, 232);
                width: 20rpx;
                border-radius: 20rpx;
              "
              :style="{ height: 20 + item * 15 + 'rpx' }"
            ></view>
          </view>
        </view>
        <image
          src="http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/free_bottom_bg.png"
          mode="widthFix"
          style="width: 100%"
        ></image>
      </view>
    </view>
    <view class="bottom-fixed flex flex-ai-center flex-js-center">
      <!-- 点击按钮 -->
      <view class="btn" v-if="typeStatus == 'none'" @click="handleStart"
        >跟{{ roleName }}练口语</view
      >
      <!-- 进度条 -->
      <view class="progress" v-if="typeStatus == 'loading'">
        <TnLineProgress
          :percent="progressPercent"
          :duration="duration"
          show-percent
          stripe-animated="false"
          height="80"
          active-color="#4B49E8"
        >
          <view class="flex flex-js-sb font-size-22">
            <text>即将接通...</text>
          </view>
        </TnLineProgress>
      </view>
      <!-- 点击说话 -->
      <view class="speak flex" v-if="typeStatus == 'start'">
        <view style="display: flex; z-index: 999" v-if="isPlayEnd">
          <view
            class="speak-btn flex flex-ai-center flex-js-center"
            @click="handleClose"
          >
            <image
              src="@/static/imgs/icons/tel_close_icon.png"
              mode="widthFix"
            ></image>
          </view>
          <button
            class="flex flex-ai-center flex-js-center mr-16 chat-btn"
            size="default"
            @click="onChatBtnClick"
            :disabled="isDisabledBtn"
            :style="{ background: isDisabledBtn ? '#AFAED1' : '#4B49E8' }"
          >
            {{ [1, 2].includes(chatBtnStatus) ? '点击对话' : '点击发送' }}
          </button>
        </view>
      </view>
      <!-- 说话中 -->
      <!-- 	<view class="speak flex" v-if="typeStatus == 'start' && animation == true">
				<view class="speak-content speak-content-active flex flex-ai-center flex-js-center mr-16" >
					<image src="http://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/hr-wechat/static/speak-img.png"
						style="width: 64rpx;height: 38rpx;" class="" mode=""></image>
				</view>
				<view class="speak-btn flex flex-ai-center flex-js-center">
					<image src="../../static/imgs/mic.png"></image>
				</view>
			</view> -->
    </view>
  </view>
  <!-- 提示答案 -->
  <TnPopup
    v-model="showPopup"
    class="popup-box"
    open-direction="bottom"
    :radius="30"
    top="54px"
  >
    <view class="plr-16 popup-main">
      <view class="popup-title flex flex-js-sb flex-ai-center">
        <view></view>
        <view class="font-size-16 font-color-c333 font-w-bold"
          >你可以这样说</view
        >
        <image
          class="close-icon"
          src="../../../static/imgs/close.png"
          @click="handleClosePopup"
        ></image>
      </view>
      <view class="popup-contnet mt-6">
        <view
          style="text-align: center"
          class="mt-40"
          v-if="tipsList.length == 0"
        >
          <TnLoading
            show
            animation
            duration="3"
            time-function="ease-in-out"
            size="90px"
          />
          <view class="mt-12">加载中，请稍等</view>
        </view>
        <view v-else>
          <view
            class="flex-1 flex items pa-12 br-16 flex-js-sb mb-12 bg-color-white"
            v-for="(item, index) in tipsList"
            :key="index"
          >
            <view class="">
              <view class="flex">
                <view
                  class="mr-8 items-line"
                  @click="handleClick('send', item.line)"
                  >{{ item.line }}
                </view>
                <view class="flex mt-2">
                  <image
                    class="translate-icon"
                    :src="item.isTranslate ? translateBlue : translateBlack"
                    mode=""
                    @click="handleClick('fanyi', item.line, index)"
                  ></image>
                </view>
              </view>
              <view class="split-line mtb-8" v-if="item.translate"></view>
              <view class="mt-4" v-if="item.translate">{{
                item.translate
              }}</view>
            </view>
          </view>
        </view>
      </view>
      <!-- <view class="popup-footer pt-10">
        <view class="footer-btn flex flex-ai-center flex-js-center">
          <image
            class="icon radius-50"
            src="../../../static/imgs/index/expert-video.png"
            @touchstart.stop="startRecord"
            @touchend.stop="endRecord"
          >
          </image>
        </view>
        <view class="font-bold font-size-14 font-color-c191919 mt-4"
          >按住说话</view
        >
      </view> -->
    </view>
  </TnPopup>
</template>

<style lang="scss" scoped>
@import './styles/index.scss';
</style>
